package geometry;

/**
 *
 * @author różański
 */
public class Segment {

    private Vertex begin, end;
    private double length;
    private boolean obstacle;
    private double a, b; //wspolczynniki prostej na ktorej lezy ten odcinek
    private boolean isVertical = false;
    public Segment(Vertex a, Vertex b) {
        this.begin = a;
        this.end = b;
        this.length = Math.sqrt((a.getX() - b.getX()) * (a.getX() - b.getX()) + (a.getY() - b.getY()) * (a.getY() - b.getY()));
        double diffX = begin.getX() - end.getX();
        if(diffX == 0) {
            isVertical = true;
            a = null;
            b = null;
        }
        else {
        double diffY = begin.getY() - end.getY();
        
        this.a = diffY / diffX;
        this.b = begin.getY() - begin.getX() * this.a;
        }
    }

    public Vertex getBegin() {
        return begin;
    }

    public Vertex getEnd() {
        return end;
    }

    public double getLength() {
        return length;
    }

    public boolean isObstacle() {
        return obstacle;
    }

    public void setObstacle(boolean obstacle) {
        this.obstacle = obstacle;
    }

    public double getA() {
        return a;
    }

    public double getB() {
        return b;
    }

    public boolean isVertical() {
        return isVertical;
    }
    public boolean intersect(Segment seg) {
        Vertex D = getEnd();
        Vertex C = getBegin();
        Vertex A = seg.getBegin();
        Vertex B = seg.getEnd();
        double sideA = (A.getX() - C.getX()) * (D.getY() - C.getY())
                - (D.getX() - C.getX()) * (A.getY() - C.getY());
        double sideB = (B.getX() - C.getX()) * (D.getY() - C.getY())
                - (D.getX() - C.getX()) * (B.getY() - C.getY());
        double sideC = (C.getX() - A.getX()) * (B.getY() - A.getY())
                - (B.getX() - A.getX()) * (C.getY() - A.getY());
        double sideD = (D.getX() - A.getX()) * (B.getY() - A.getY())
                - (B.getX() - A.getX()) * (D.getY() - A.getY());

        return Math.signum(sideA) * Math.signum(sideB) == -1
                && Math.signum(sideC) * Math.signum(sideD) == -1;
    }

    public Vertex intersectionPoint(Segment seg) {
        if (intersect(seg)) {
            if(isVertical) {
                if(seg.isVertical()) {
                    return null;
                }
                else return new Vertex(begin.getX(),seg.getA()*begin.getX() + seg.getB());
            }
            if (seg.isVertical()) {
                return new Vertex(seg.getBegin().getX(), a*seg.getBegin().getX() + b);
            }
            
            double x = (seg.getB() - b) / (a - seg.getA());
            double y = a * x + b;
            return new Vertex(x, y);
        }
        return null;
    }

    @Override
    public String toString() {
        return begin + "-" + end;
    }
}
